<script lang="ts" context="module">
  import { isEmpty } from "@util/checker";
  import type { Column, TableContext } from "./conf";
  import { getContext } from "svelte";
</script>

<script lang="ts">
  import { createEventDispatcher } from "svelte";
  export let col: Column;
  export let value = "";
  let oldVal = value;
  const { isDirty$, isEditingRowDataState$ } =
    getContext<TableContext>("table");
  const dispatch = createEventDispatcher();
  function handleBlur() {
    console.log("dddd->", oldVal, value, oldVal !== value);
    let valid = true;
    let tip = "";
    if (col.options?.editOption?.required && isEmpty(value)) {
      console.warn(
        `key:${col.key} (oldVal:${oldVal} and newVal:${value}) need required, but value is emtpy`
      );
      valid = false;
      tip = `${col.title}不能为空`;
    }
    $isEditingRowDataState$[col.key] = {
      oldValue: oldVal,
      newValue: value,
      valid,
      tip,
    };
    console.log("$isEditingRowDataState$==>", $isEditingRowDataState$);
    isEditingRowDataState$.set($isEditingRowDataState$);
    if (oldVal !== value) {
      isDirty$.set(true);
      dispatch("update-cell", {
        cellKey: col.key,
        val: value,
      });
    }
  }
  function inputCellValueChecker(node, val) {
    let valid = true;
    let tip = "";
    if (col.options?.editOption?.required && isEmpty(value)) {
      console.warn(
        `key:${col.key} (oldVal:${oldVal} and newVal:${value}) need required, but value is emtpy`
      );
      valid = false;
      tip = `${col.title}不能为空`;
    }
    $isEditingRowDataState$[col.key] = {
      oldValue: oldVal,
      newValue: value,
      valid,
      tip,
    };
    console.log("=====init $isEditingRowDataState$==>", $isEditingRowDataState$);
    isEditingRowDataState$.set($isEditingRowDataState$);
    return {
      update(val) {
        console.warn('inputcell--popup')
        handleBlur()
      }
    }
  }
  $: isValid =
    !$isEditingRowDataState$[col.key] || $isEditingRowDataState$[col.key].valid;
  $: errTip = $isEditingRowDataState$[col.key]?.tip;
</script>

<div data-tip={errTip || null}>
  <input
    use:inputCellValueChecker={value}
    type="text"
    class="input-cell bar-bg focus-visible:outline-[#66b851]"
    class:invalid={!isValid}
    bind:value
  />
</div>

<style lang="postcss">
  .input-cell {
    @apply w-full rounded px-2 text-lg font-normal border border-[#66b851];
    height: calc(var(--dt-row-height) * 1px);
  }
  .invalid {
    @apply border-red-500;
  }
</style>
